<template>

    <div class="editor" style="clear: both">
        <quill-editor ref="editor" theme="snow" v-model:content="internalContent" :options="editorOptions"
            content-type="html"></quill-editor>
    </div>


</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, toRaw, reactive, onMounted } from 'vue';
import { QuillEditor } from '@vueup/vue-quill';
import Quill from 'quill'; // 确保也从 quill 引入 Quill 本身
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import 'quill/dist/quill.core.css'
import 'quill-image-uploader/dist/quill.imageUploader.min.css';

import ImageUploader from 'quill-image-uploader';
import BlotFormatter from 'quill-blot-formatter';
import { uploadPicture } from '../../api/uploadApi.ts'; // 引入上传图片的api
import { compressImage } from '../../until/compressImage.ts'; // 确保压缩函数路径正确

import '../commonUse/QuillFont.css'; // 字体和字体大小的自定义文件
import '../commonUse/QuillLineHeight.css'; // 行高的自定义文件
// 在 Quill 中注册 ImageUploader
if (!Quill.imports['modules/imageUploader']) {
    Quill.register("modules/imageUploader", ImageUploader);
}
// 注册 BlotFormatter
if (!Quill.imports['modules/blotFormatter']) {
    Quill.register('modules/blotFormatter', BlotFormatter);
}
interface Props {
    initialContent?: string;
}

const editor = ref();
const props = defineProps<Props>();
const emit = defineEmits(['contentUpdated']);
const internalContent = ref(props.initialContent);

// 初始化时同步 content prop
watch(internalContent, (newValue) => {
    emit('contentUpdated', newValue);
});

// 监听 initialContent 的变化并更新 internalContent
watch(() => props.initialContent, (newValue) => {

    if (newValue) {
        internalContent.value = newValue; // 同步变化到内部状态和编辑器        
    } else {
        const quill = toRaw(editor.value);
        if (quill) {
            quill.setContents('');
        } else {
            console.log('quill是空的');

        }
    }
}, { immediate: true }); // immediate: true 确保初始值也会触发更新



// 设置行高的配置======start
const lineHeight = ['1', '1.25', '1.5', '1.75', '2.5', '3', '5'];
const parchment = Quill.import('parchment');
const lineHeightConfig = {
    scope: parchment.Scope.INLINE,
    whitelist: lineHeight,
};
const lineHeightStyle = new parchment.Attributor.Style(
    'lineHeight',
    'line-height',
    lineHeightConfig,
);
Quill.register({ 'formats/lineHeight': lineHeightStyle }, true);

// 设置字体大小
const fontSizeStyle = Quill.import('attributors/style/size'); // 引入这个后会把样式写在style上
fontSizeStyle.whitelist = [
    '12px',
    '14px',
    '16px',
    '18px',
    '20px',
    '22px',
    '24px',
    '28px',
    '30px',
];
// 设置字体
const fontStyle = Quill.import('attributors/style/font'); // 引入这个后会把样式写在style上
fontStyle.whitelist = [
    'SimSun', // 宋体
    'SimHei', // 黑体
    'STFANGSO', // 华文仿宋
    'Microsoft-YaHei', // 微软雅黑
    'KaiTi', // 楷体
    'FangSong', // 仿宋
    'STKAITI', // 华文楷体
    'Arial',
    'Times-New-Roman',
    'sans-serif',
];

Quill.register(fontSizeStyle, true);
Quill.register(fontStyle, true);



const editorOptions = reactive({
    modules: {
        toolbar: {
            container: [
                ['bold', 'italic', 'underline', 'strike'],
                ['blockquote', 'code-block'],
                [{ header: 1 }, { header: 2 }],
                [{ list: 'ordered' }, { list: 'bullet' }],
                [{ script: 'sub' }, { script: 'super' }],
                [{ indent: '-1' }, { indent: '+1' }],
                [{ direction: 'rtl' }],

                [{ header: [1, 2, 3, 4, 5, 6, false] }],
                [{ color: [] }, { background: [] }],
                [{ font: fontStyle.whitelist }], // 字体
                [{ lineheight: lineHeight }], // 设置行高
                [{ size: fontSizeStyle.whitelist }], // 字体大小
                [{ align: [] }],// 对齐方式
                ['clean'],
                ['link', 'image', 'video'] // 超链接 图片 视频
            ],
            handlers: {
                // 如果有特定的handler函数需要在这里添加
                lineheight: (value: any) => {
                    const quill = editor.value.getQuill();
                    if (quill) {

                        if (value) {
                            quill.format('lineHeight', value);
                        }

                    } else {
                        console.log('quill是空的:hg');
                    }

                }

            },
            imageUploader: {
                upload: async (file: any) => {

                    try {
                        const compressedFile = await compressImage(file); // 假设 compressImage 正确返回 File 或 Blob
                        const formData = new FormData();
                        formData.append("file", compressedFile);
                        const response = await uploadPicture(formData); // 直接等待此异步操作完成
                        let imageUrl = response; //response 就是图片 URL
                        imageUrl = encodeURI(imageUrl); // 确保 URL 是有效的
                        console.log(imageUrl);
                        //const imageUrl = "https://measurement-alliance-collection.oss-cn-beijing.aliyuncs.com/2024-06/aba262b5-1a80-419d-9527-cc327074cc87.png";
                        const quill = toRaw(editor.value);
                        const range = quill.getSelection(true); // 如果没有选区，默认在文档末尾插入
                        if (range && range.index !== -1) {

                            quill.setSelection(range.index + 1);
                            return imageUrl; // 成功后返回图片 URL
                        } else {
                            throw new Error('No valid selection found for image insertion.');
                        }
                    } catch (error) {
                        console.error('Error during image upload or insertion:', error);
                        throw error; // 向外传递错误
                    }
                }

            },

            blotFormatter: {
                // 如果需要其他配置，请在此添加
            }
        }
    },
    placeholder: '请输入内容...'

});

</script>

<style></style>
